# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Martell Malone <martellmalone@gmail.com>

# controls the compiler that builds the crt with _variant
_variant=clang
#_variant=gcc

_realname=crt
_mingw_suff=mingw-w64-cross
pkgname="${_mingw_suff}-${_realname}-git"
replaces="${_mingw_suff}-${_realname}"
provides=("${_mingw_suff}-${_realname}")
conflicts=("${_mingw_suff}-${_realname}")
pkgver=5.0.0.4592.90b8472
pkgrel=1
pkgdesc='MinGW-w64 CRT for cross-compiler'
arch=('i686' 'x86_64')
url='http://mingw-w64.sourceforge.net'
license=('custom')
groups=("${_mingw_suff}-toolchain" "${_mingw_suff}")
depends=("${_mingw_suff}-headers")

if [ "${_variant}" = "clang" ]; then
  makedepends=("git" "clang" "lld")
  pkgname="${_mingw_suff}-${_realname}-clang-git"
  _imptool=genlib
else
  makedepends=("git" "${_mingw_suff}-gcc" "${_mingw_suff}-binutils")
  _imptool=dlltool
fi

options=('!strip' 'staticlibs' '!emptydirs' '!buildflags')
source=("mingw-w64"::"git://git.code.sf.net/p/mingw-w64/mingw-w64"
        "0001-Handle-__CTOR_LIST__-internally-within-mingw-w64.patch")

md5sums=('SKIP'
         'ca109611eaeb24c95d274388425a3bc1')

_targets="x86_64-w64-mingw32 i686-w64-mingw32 armv7-w64-mingw32"

pkgver() {
  cd "${srcdir}/mingw-w64"
  local _major=$(head -n 16 mingw-w64-headers/crt/_mingw_mac.h | grep '__MINGW64_VERSION_MAJOR' | sed -e 's/.* //' | tr '\n' '.' | sed 's/.$/\n/')
  local _minor=$(head -n 16 mingw-w64-headers/crt/_mingw_mac.h | grep '__MINGW64_VERSION_MINOR' | sed -e 's/.* //' | tr '\n' '.' | sed 's/.$/\n/')
  local _rev=0
  printf "%s.%s.%s.%s.%s" ${_major} ${_minor} ${_rev} "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
}

prepare() {
  cd "${srcdir}/mingw-w64"
  git am "${srcdir}/"0001-Handle-__CTOR_LIST__-internally-within-mingw-w64.patch
}

build() {
  for _target in ${_targets}; do
    msg "Building ${_target} CRT"
  case "$_target" in
    i686*)
      _crt_configure_args="--disable-lib64 --enable-lib32"
    ;;
    x86_64*)
      _crt_configure_args="--disable-lib32 --enable-lib64"
    ;;
    armv7*)
      _crt_configure_args="--disable-lib32 --disable-lib64 --enable-libarm32"
    ;;
  esac
    mkdir -p ${srcdir}/crt-${_target} && cd ${srcdir}/crt-${_target}

    #--with-host-libstdcxx="-lstdc++ -lsupc++"
    # we must stitch to this once i get it built / working :)
    # AS = as

    if [ "${_variant}" = "clang" ]; then
      export CC="${_target}-clang" CXX="${_target}-clang++" AR="llvm-ar" RANLIB="llvm-ranlib" DLLTOOL="${_target}-dlltool" LD="lld"
    fi

    if [ "${_imptool}" = "genlib" ]; then
      _crt_configure_args+=" --with-genlib"
    fi

    ${srcdir}/mingw-w64/mingw-w64-crt/configure \
    --build=${CHOST} \
    --prefix=/opt/${_target} \
    --host=${_target} \
    --enable-wildcard \
    ${_crt_configure_args}

    make
  done
}

package() {
  for _target in ${_targets}; do
    msg "Installing ${_target} crt"
    cd ${srcdir}/crt-${_target}
    make DESTDIR=${pkgdir} install
  done
}
